<template>
  <div class="dashboard-container">
    <!-- 欢迎横幅 -->
    <el-card shadow="never" class="welcome-banner mb-5">
      <div class="welcome-content">
        <div class="welcome-text">
          <h2 class="welcome-title">{{ greetings }}</h2>
          <p class="welcome-subtitle">欢迎使用电商销售日报管理系统</p>
          <p class="welcome-date">{{ currentDateStr }}</p>
        </div>
        <div class="welcome-actions">
          <el-button type="primary" @click="goToDailyDashboard">
            <el-icon><TrendCharts /></el-icon>
            查看今日销售
          </el-button>
          <el-button @click="goToSalesTable">
            <el-icon><DataBoard /></el-icon>
            销售数据管理
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 核心业务数据统计 -->
    <el-row :gutter="20" class="mb-5">
      <!-- 今日销售额 -->
      <el-col :span="6" :xs="24" class="mb-xs-3">
        <el-card shadow="never" class="metric-card sales-card">
          <div class="metric-header">
            <span class="metric-title">今日销售额</span>
            <el-tag type="success" size="small">实时</el-tag>
          </div>
          <div class="metric-content">
            <div class="metric-value">¥{{ formatNumber(salesData.todaySales) }}</div>
            <div class="metric-trend" :class="getTrendClass(salesData.salesGrowth)">
              <el-icon>
                <Top v-if="salesData.salesGrowth > 0" />
                <Bottom v-else-if="salesData.salesGrowth < 0" />
                <Minus v-else />
              </el-icon>
              {{ formatPercent(salesData.salesGrowth) }}%
            </div>
          </div>
          <div class="metric-footer">
            <span>昨日：¥{{ formatNumber(salesData.yesterdaySales) }}</span>
          </div>
        </el-card>
      </el-col>

      <!-- 月度完成率 -->
      <el-col :span="6" :xs="24" class="mb-xs-3">
        <el-card shadow="never" class="metric-card progress-card">
          <div class="metric-header">
            <span class="metric-title">月度完成率</span>
            <el-tag type="primary" size="small">月度</el-tag>
          </div>
          <div class="metric-content">
            <div class="metric-value">{{ formatPercent(salesData.monthlyProgress) }}%</div>
            <el-progress 
              :percentage="salesData.monthlyProgress" 
              :color="getProgressColor(salesData.monthlyProgress)"
              :stroke-width="8"
              class="mt-2"
            />
          </div>
          <div class="metric-footer">
            <span>目标：¥{{ formatNumber(salesData.monthlyTarget) }}</span>
          </div>
        </el-card>
      </el-col>

      <!-- 客单价 -->
      <el-col :span="6" :xs="24" class="mb-xs-3">
        <el-card shadow="never" class="metric-card price-card">
          <div class="metric-header">
            <span class="metric-title">平均客单价</span>
            <el-tag type="warning" size="small">日均</el-tag>
          </div>
          <div class="metric-content">
            <div class="metric-value">¥{{ formatNumber(salesData.avgOrderValue) }}</div>
            <div class="metric-trend" :class="getTrendClass(salesData.aovGrowth)">
              <el-icon>
                <Top v-if="salesData.aovGrowth > 0" />
                <Bottom v-else-if="salesData.aovGrowth < 0" />
                <Minus v-else />
              </el-icon>
              {{ formatPercent(salesData.aovGrowth) }}%
            </div>
          </div>
          <div class="metric-footer">
            <span>订单数：{{ salesData.todayOrders }}</span>
          </div>
        </el-card>
      </el-col>

      <!-- 转化率 -->
      <el-col :span="6" :xs="24" class="mb-xs-3">
        <el-card shadow="never" class="metric-card conversion-card">
          <div class="metric-header">
            <span class="metric-title">转化率</span>
            <el-tag type="info" size="small">实时</el-tag>
          </div>
          <div class="metric-content">
            <div class="metric-value">{{ formatPercent(salesData.conversionRate) }}%</div>
            <div class="metric-trend" :class="getTrendClass(salesData.conversionGrowth)">
              <el-icon>
                <Top v-if="salesData.conversionGrowth > 0" />
                <Bottom v-else-if="salesData.conversionGrowth < 0" />
                <Minus v-else />
              </el-icon>
              {{ formatPercent(salesData.conversionGrowth) }}%
            </div>
          </div>
          <div class="metric-footer">
            <span>访客：{{ salesData.todayVisitors }}</span>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20">
      <!-- 销售趋势图表 -->
      <el-col :xs="24" :span="16">
        <el-card shadow="never">
          <template #header>
            <div class="flex-x-between">
              <span class="chart-title">销售趋势分析</span>
              <el-radio-group v-model="salesTrendDateRange" size="small">
                <el-radio-button :value="7">近7天</el-radio-button>
                <el-radio-button :value="30">近30天</el-radio-button>
                <el-radio-button :value="90">近3个月</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <ECharts :options="salesTrendChartOptions" height="400px" />
        </el-card>
      </el-col>

      <!-- 快捷操作和系统状态 -->
      <el-col :xs="24" :span="8">
        <el-card shadow="never" class="mb-4">
          <template #header>
            <span class="chart-title">快捷操作</span>
          </template>
          <div class="quick-actions-grid">
            <el-button 
              type="primary" 
              class="quick-action-btn"
              @click="goToDailyDashboard"
            >
              <el-icon><TrendCharts /></el-icon>
              日报看板
            </el-button>
            <el-button 
              type="success" 
              class="quick-action-btn"
              @click="goToSalesTable"
            >
              <el-icon><DataBoard /></el-icon>
              销售数据
            </el-button>
            <el-button 
              type="warning" 
              class="quick-action-btn"
              @click="goToSupplyTable"
            >
              <el-icon><Box /></el-icon>
              供应链
            </el-button>
            <div class="quick-action-dropdown">
              <el-dropdown @command="handleExportReport" :disabled="exportLoading">
                <el-button 
                  type="info" 
                  class="quick-action-btn"
                  :loading="exportLoading"
                >
                  <el-icon><Download /></el-icon>
                  导出报告
                  <el-icon class="el-icon--right"><arrow-down /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="csv">
                      <el-icon><Document /></el-icon>
                      导出CSV格式
                    </el-dropdown-item>
                    <el-dropdown-item command="excel">
                      <el-icon><Document /></el-icon>
                      导出Excel格式
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </div>
        </el-card>

        <el-card shadow="never">
          <template #header>
            <span class="chart-title">系统状态</span>
          </template>
          <div class="system-status">
            <div class="status-item">
              <div class="status-label">在线用户</div>
              <div class="status-value">
                {{ systemStatus.onlineUsers }}人
                <span class="status-indicator" :style="{ color: getStatusColor(systemStatus.onlineUsers, 'count') }">
                  <el-icon><Connection /></el-icon>
                </span>
              </div>
            </div>
            <div class="status-item">
              <div class="status-label">服务器状态</div>
              <div class="status-value">
                <span class="status-badge" :class="systemStatus.serverStatus === 'running' ? 'status-running' : 'status-error'">
                  {{ systemStatus.serverStatus === 'running' ? '运行中' : '异常' }}
                </span>
              </div>
            </div>
            <div class="status-item">
              <div class="status-label">CPU使用率</div>
              <div class="status-value">
                <span :style="{ color: getStatusColor(systemStatus.cpuUsage) }">
                  {{ systemStatus.cpuUsage }}%
                </span>
                <div class="status-bar">
                  <div 
                    class="status-bar-fill" 
                    :style="{ 
                      width: systemStatus.cpuUsage + '%',
                      backgroundColor: getStatusColor(systemStatus.cpuUsage)
                    }"
                  ></div>
                </div>
              </div>
            </div>
            <div class="status-item">
              <div class="status-label">内存使用率</div>
              <div class="status-value">
                <span :style="{ color: getStatusColor(systemStatus.memoryUsage) }">
                  {{ systemStatus.memoryUsage }}%
                </span>
                <div class="status-bar">
                  <div 
                    class="status-bar-fill" 
                    :style="{ 
                      width: systemStatus.memoryUsage + '%',
                      backgroundColor: getStatusColor(systemStatus.memoryUsage)
                    }"
                  ></div>
                </div>
              </div>
            </div>
            <div class="status-item">
              <div class="status-label">磁盘使用率</div>
              <div class="status-value">
                <span :style="{ color: getStatusColor(systemStatus.diskUsage) }">
                  {{ systemStatus.diskUsage }}%
                </span>
                <div class="status-bar">
                  <div 
                    class="status-bar-fill" 
                    :style="{ 
                      width: systemStatus.diskUsage + '%',
                      backgroundColor: getStatusColor(systemStatus.diskUsage)
                    }"
                  ></div>
                </div>
              </div>
            </div>
            <div class="status-item">
              <div class="status-label">数据更新</div>
              <div class="status-value">{{ systemStatus.dataUpdateTime }}</div>
            </div>
            <div class="status-item">
              <div class="status-label">系统版本</div>
              <div class="status-value">{{ systemStatus.version }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "Dashboard",
  inheritAttrs: false,
});

import { dayjs } from "element-plus";
import { useUserStore } from "@/store/modules/user.store";
import { useDateFormat } from "@vueuse/core";
import { Connection, Failed, TrendCharts, DataBoard, Box, Download, Top, Bottom, Minus, Document, ArrowDown } from "@element-plus/icons-vue";
import { useOnlineCount } from "@/hooks/websocket/services/useOnlineCount";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import * as ExcelJS from 'exceljs';

const router = useRouter();
const userStore = useUserStore();

// 在线用户数量组件相关
const { onlineUserCount, lastUpdateTime, isConnected } = useOnlineCount();

// 格式化时间戳
const formattedTime = computed(() => {
  if (!lastUpdateTime.value) return "--";
  return useDateFormat(lastUpdateTime, "HH:mm:ss").value;
});

// 当前日期
const currentDateStr = computed(() => {
  return dayjs().format("YYYY年MM月DD日 dddd");
});

// 问候语：根据当前小时返回不同问候语
const greetings = computed(() => {
  const hours = new Date().getHours();
  const nickname = userStore.userInfo.nickname || "用户";
  
  if (hours >= 6 && hours < 9) {
    return `早上好，${nickname}！新的一天开始了`;
  } else if (hours >= 9 && hours < 12) {
    return `上午好，${nickname}！让我们查看今日销售情况`;
  } else if (hours >= 12 && hours < 14) {
    return `中午好，${nickname}！午间时光也要关注业务数据`;
  } else if (hours >= 14 && hours < 18) {
    return `下午好，${nickname}！下午的销售冲刺时间到了`;
  } else if (hours >= 18 && hours < 22) {
    return `晚上好，${nickname}！让我们总结今日的销售成果`;
  } else {
    return `夜深了，${nickname}！记得早点休息`;
  }
});

// 销售数据
const salesData = ref({
  todaySales: 156780.50,
  yesterdaySales: 142350.80,
  salesGrowth: 10.12,
  monthlyProgress: 68.5,
  monthlyTarget: 2500000,
  avgOrderValue: 268.50,
  aovGrowth: 5.8,
  todayOrders: 584,
  conversionRate: 4.58,
  conversionGrowth: 2.3,
  todayVisitors: 12750
});

// 销售趋势日期范围
const salesTrendDateRange = ref(7);
const exportLoading = ref(false);

// 系统状态模拟数据
const systemStatus = ref({
  onlineUsers: 0,
  dataUpdateTime: '',
  version: 'v2.4.0',
  serverStatus: 'running',
  cpuUsage: 0,
  memoryUsage: 0,
  diskUsage: 0
});

// 模拟系统状态数据
const simulateSystemStatus = () => {
  // 模拟在线用户数量变化
  systemStatus.value.onlineUsers = Math.floor(Math.random() * 50) + 10;
  
  // 模拟CPU使用率
  systemStatus.value.cpuUsage = Math.floor(Math.random() * 30) + 20;
  
  // 模拟内存使用率
  systemStatus.value.memoryUsage = Math.floor(Math.random() * 40) + 40;
  
  // 模拟磁盘使用率
  systemStatus.value.diskUsage = Math.floor(Math.random() * 20) + 60;
  
  // 更新数据时间
  systemStatus.value.dataUpdateTime = dayjs().format('HH:mm:ss');
};

// 定时更新系统状态
let statusTimer: NodeJS.Timeout | null = null;

onMounted(() => {
  // 初始化系统状态
  simulateSystemStatus();
  
  // 每30秒更新一次系统状态
  statusTimer = setInterval(() => {
    simulateSystemStatus();
  }, 30000);
});

onUnmounted(() => {
  if (statusTimer) {
    clearInterval(statusTimer);
  }
});

// 获取状态指示器颜色
const getStatusColor = (value: number, type: 'usage' | 'count' = 'usage') => {
  if (type === 'count') {
    return value > 0 ? '#67c23a' : '#f56c6c';
  }
  
  if (value < 50) return '#67c23a';
  if (value < 80) return '#e6a23c';
  return '#f56c6c';
};

// 销售趋势图表配置
const salesTrendChartOptions = computed(() => {
  // 模拟数据，实际应该从API获取
  const dates = [];
  const salesData = [];
  const ordersData = [];
  
  for (let i = salesTrendDateRange.value - 1; i >= 0; i--) {
    dates.push(dayjs().subtract(i, 'day').format('MM-DD'));
    salesData.push(Math.floor(Math.random() * 50000) + 100000);
    ordersData.push(Math.floor(Math.random() * 200) + 400);
  }

  return {
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: 'cross'
      }
    },
    legend: {
      data: ["销售额", "订单数"],
      bottom: 0,
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "10%",
      containLabel: true,
    },
    xAxis: {
      type: "category",
      data: dates,
    },
    yAxis: [
      {
        type: "value",
        name: "销售额(元)",
        position: "left",
        splitLine: {
          show: true,
          lineStyle: {
            type: "dashed",
          },
        },
      },
      {
        type: "value",
        name: "订单数",
        position: "right",
        splitLine: {
          show: false,
        },
      }
    ],
    series: [
      {
        name: "销售额",
        type: "line",
        yAxisIndex: 0,
        data: salesData,
        areaStyle: {
          color: "rgba(64, 158, 255, 0.1)",
        },
        smooth: true,
        itemStyle: {
          color: "#4080FF",
        },
        lineStyle: {
          color: "#4080FF",
        },
      },
      {
        name: "订单数",
        type: "bar",
        yAxisIndex: 1,
        data: ordersData,
        itemStyle: {
          color: "#67C23A",
        },
      },
    ],
  };
});

// 格式化数字
const formatNumber = (value: number) => {
  return value.toLocaleString();
};

// 格式化百分比
const formatPercent = (value: number) => {
  return Math.abs(value).toFixed(2);
};

// 获取趋势样式类
const getTrendClass = (value: number) => {
  if (value > 0) return 'trend-up';
  if (value < 0) return 'trend-down';
  return 'trend-neutral';
};

// 获取进度条颜色
const getProgressColor = (value: number) => {
  if (value >= 80) return '#67c23a';
  if (value >= 60) return '#e6a23c';
  if (value >= 40) return '#f56c6c';
  return '#909399';
};

// 导航方法
const goToDailyDashboard = () => {
  router.push('/reportcenter/daily-dashboard');
};

const goToSalesTable = () => {
  router.push('/reportcenter/salestable');
};

const goToSupplyTable = () => {
  router.push('/reportcenter/supplytable');
};

// 导出今日报告
const exportTodayReport = async () => {
  exportLoading.value = true;
  try {
    // 创建报告内容
    const reportData = {
      reportDate: dayjs().format('YYYY-MM-DD'),
      reportTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
      salesData: salesData.value,
      systemInfo: {
        onlineUsers: onlineUserCount.value,
        lastUpdate: formattedTime.value,
        version: 'v2.4.0'
      }
    };

    // 生成CSV格式的报告
    const csvContent = generateCSVReport(reportData);
    
    // 创建下载链接
    const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
    const link = document.createElement('a');
    const url = URL.createObjectURL(blob);
    
    link.setAttribute('href', url);
    link.setAttribute('download', `销售日报_${dayjs().format('YYYYMMDD')}.csv`);
    link.style.visibility = 'hidden';
    
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    
    URL.revokeObjectURL(url);
    
    ElMessage.success('今日报告导出成功！');
  } catch (error) {
    console.error('导出失败:', error);
    ElMessage.error('导出失败，请重试');
  } finally {
    exportLoading.value = false;
  }
};

// 生成CSV格式报告
const generateCSVReport = (data: any) => {
  const { reportDate, reportTime, salesData, systemInfo } = data;
  
  let csv = '\uFEFF'; // BOM for UTF-8
  csv += '电商销售日报\n';
  csv += `报告日期,${reportDate}\n`;
  csv += `生成时间,${reportTime}\n`;
  csv += '\n';
  
  csv += '核心指标\n';
  csv += '指标名称,数值,单位,变化趋势\n';
  csv += `今日销售额,${salesData.todaySales},元,${salesData.salesGrowth > 0 ? '+' : ''}${salesData.salesGrowth}%\n`;
  csv += `月度完成率,${salesData.monthlyProgress},%,目标${salesData.monthlyTarget}元\n`;
  csv += `平均客单价,${salesData.avgOrderValue},元,${salesData.aovGrowth > 0 ? '+' : ''}${salesData.aovGrowth}%\n`;
  csv += `转化率,${salesData.conversionRate},%,${salesData.conversionGrowth > 0 ? '+' : ''}${salesData.conversionGrowth}%\n`;
  csv += '\n';
  
  csv += '详细数据\n';
  csv += '项目,数值\n';
  csv += `昨日销售额,${salesData.yesterdaySales}元\n`;
  csv += `今日订单数,${salesData.todayOrders}笔\n`;
  csv += `今日访客数,${salesData.todayVisitors}人\n`;
  csv += `月度目标,${salesData.monthlyTarget}元\n`;
  csv += '\n';
  
  csv += '系统信息\n';
  csv += '项目,状态\n';
  csv += `在线用户,${systemInfo.onlineUsers}人\n`;
  csv += `数据更新时间,${systemInfo.lastUpdate}\n`;
  csv += `系统版本,${systemInfo.version}\n`;
  
  return csv;
};

// 处理导出报告
const handleExportReport = async (command: string) => {
  if (command === 'csv') {
    await exportTodayReport();
  } else if (command === 'excel') {
    await exportExcelReport();
  }
};

// 导出Excel格式报告
const exportExcelReport = async () => {
  exportLoading.value = true;
  try {
    const workbook = new ExcelJS.Workbook();
    const worksheet = workbook.addWorksheet('销售日报');

    // 设置列宽
    worksheet.columns = [
      { header: '项目', key: 'item', width: 20 },
      { header: '数值', key: 'value', width: 15 },
      { header: '单位', key: 'unit', width: 10 },
      { header: '备注', key: 'note', width: 25 }
    ];

    // 添加标题
    worksheet.mergeCells('A1:D1');
    const titleCell = worksheet.getCell('A1');
    titleCell.value = '电商销售日报';
    titleCell.font = { size: 16, bold: true };
    titleCell.alignment = { horizontal: 'center' };

    // 添加报告信息
    worksheet.addRow(['报告日期', dayjs().format('YYYY-MM-DD'), '', '']);
    worksheet.addRow(['生成时间', dayjs().format('YYYY-MM-DD HH:mm:ss'), '', '']);
    worksheet.addRow(['', '', '', '']); // 空行

    // 添加核心指标标题
    worksheet.mergeCells('A5:D5');
    const metricsTitle = worksheet.getCell('A5');
    metricsTitle.value = '核心指标';
    metricsTitle.font = { size: 14, bold: true };
    metricsTitle.alignment = { horizontal: 'center' };

    // 添加表头
    worksheet.addRow(['指标名称', '数值', '单位', '变化趋势']);
    const headerRow = worksheet.getRow(6);
    headerRow.font = { bold: true };
    headerRow.fill = {
      type: 'pattern',
      pattern: 'solid',
      fgColor: { argb: 'FFE6F3FF' }
    };

    // 添加核心指标数据
    worksheet.addRow([
      '今日销售额', 
      salesData.value.todaySales, 
      '元', 
      `${salesData.value.salesGrowth > 0 ? '+' : ''}${salesData.value.salesGrowth}%`
    ]);
    worksheet.addRow([
      '月度完成率', 
      salesData.value.monthlyProgress, 
      '%', 
      `目标${salesData.value.monthlyTarget}元`
    ]);
    worksheet.addRow([
      '平均客单价', 
      salesData.value.avgOrderValue, 
      '元', 
      `${salesData.value.aovGrowth > 0 ? '+' : ''}${salesData.value.aovGrowth}%`
    ]);
    worksheet.addRow([
      '转化率', 
      salesData.value.conversionRate, 
      '%', 
      `${salesData.value.conversionGrowth > 0 ? '+' : ''}${salesData.value.conversionGrowth}%`
    ]);

    worksheet.addRow(['', '', '', '']); // 空行

    // 添加详细数据标题
    worksheet.mergeCells('A12:D12');
    const detailTitle = worksheet.getCell('A12');
    detailTitle.value = '详细数据';
    detailTitle.font = { size: 14, bold: true };
    detailTitle.alignment = { horizontal: 'center' };

    // 添加详细数据
    worksheet.addRow(['项目', '数值', '', '']);
    const detailHeaderRow = worksheet.getRow(13);
    detailHeaderRow.font = { bold: true };
    detailHeaderRow.fill = {
      type: 'pattern',
      pattern: 'solid',
      fgColor: { argb: 'FFE6F3FF' }
    };

    worksheet.addRow(['昨日销售额', `${salesData.value.yesterdaySales}元`, '', '']);
    worksheet.addRow(['今日订单数', `${salesData.value.todayOrders}笔`, '', '']);
    worksheet.addRow(['今日访客数', `${salesData.value.todayVisitors}人`, '', '']);
    worksheet.addRow(['月度目标', `${salesData.value.monthlyTarget}元`, '', '']);

    worksheet.addRow(['', '', '', '']); // 空行

    // 添加系统信息
    worksheet.mergeCells('A19:D19');
    const systemTitle = worksheet.getCell('A19');
    systemTitle.value = '系统信息';
    systemTitle.font = { size: 14, bold: true };
    systemTitle.alignment = { horizontal: 'center' };

    worksheet.addRow(['项目', '状态', '', '']);
    const systemHeaderRow = worksheet.getRow(20);
    systemHeaderRow.font = { bold: true };
    systemHeaderRow.fill = {
      type: 'pattern',
      pattern: 'solid',
      fgColor: { argb: 'FFE6F3FF' }
    };

    worksheet.addRow(['在线用户', `${onlineUserCount.value}人`, '', '']);
    worksheet.addRow(['数据更新时间', formattedTime.value, '', '']);
    worksheet.addRow(['系统版本', 'v2.4.0', '', '']);

    // 设置边框
    worksheet.eachRow((row, rowNumber) => {
      if (rowNumber >= 6) {
        row.eachCell((cell) => {
          cell.border = {
            top: { style: 'thin' },
            left: { style: 'thin' },
            bottom: { style: 'thin' },
            right: { style: 'thin' }
          };
        });
      }
    });

    // 生成文件并下载
    const buffer = await workbook.xlsx.writeBuffer();
    const blob = new Blob([buffer], { 
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' 
    });
    
    const link = document.createElement('a');
    const url = URL.createObjectURL(blob);
    
    link.setAttribute('href', url);
    link.setAttribute('download', `销售日报_${dayjs().format('YYYYMMDD')}.xlsx`);
    link.style.visibility = 'hidden';
    
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    
    URL.revokeObjectURL(url);
    
    ElMessage.success('Excel报告导出成功！');
  } catch (error) {
    console.error('Excel导出失败:', error);
    ElMessage.error('Excel导出失败，请重试');
  } finally {
    exportLoading.value = false;
  }
};
</script>

<style lang="scss" scoped>
.dashboard-container {
  padding: 24px;
  background: #f5f7fa;
  min-height: calc(100vh - 84px);
}

.welcome-banner {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  
  :deep(.el-card__body) {
    padding: 30px;
  }
  
  .welcome-content {
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    .welcome-text {
      .welcome-title {
        font-size: 28px;
        font-weight: 600;
        margin: 0 0 8px 0;
      }
      
      .welcome-subtitle {
        font-size: 16px;
        opacity: 0.9;
        margin: 0 0 4px 0;
      }
      
      .welcome-date {
        font-size: 14px;
        opacity: 0.8;
        margin: 0;
      }
    }
    
    .welcome-actions {
      display: flex;
      gap: 12px;
      
      .el-button {
        padding: 12px 24px;
        font-size: 14px;
      }
    }
  }
}

.metric-card {
  height: 140px;
  transition: all 0.3s ease;
  
  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
  }
  
  :deep(.el-card__body) {
    padding: 20px;
    height: 100%;
    display: flex;
    flex-direction: column;
  }
  
  .metric-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12px;
    
    .metric-title {
      font-size: 14px;
      color: #606266;
      font-weight: 500;
    }
  }
  
  .metric-content {
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: center;
    
    .metric-value {
      font-size: 24px;
      font-weight: 600;
      color: #303133;
      margin-bottom: 8px;
    }
    
    .metric-trend {
      font-size: 12px;
      display: flex;
      align-items: center;
      gap: 4px;
      
      &.trend-up {
        color: #f56c6c;
      }
      
      &.trend-down {
        color: #67c23a;
      }
      
      &.trend-neutral {
        color: #909399;
      }
    }
  }
  
  .metric-footer {
    font-size: 12px;
    color: #909399;
    margin-top: auto;
  }
}

.chart-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

// 快捷操作按钮网格布局 - 修复为2x2布局
:deep(.quick-actions-grid) {
  display: grid !important;
  grid-template-columns: 1fr 1fr !important;
  grid-template-rows: 1fr 1fr !important;
  gap: 12px !important;
  width: 100% !important;
  
  .quick-action-btn {
    width: 100% !important;
    height: 48px !important;
    display: flex !important;
    align-items: center !important;
    justify-content: center !important;
    gap: 8px !important;
    margin: 0 !important;
    box-sizing: border-box !important;
  }
  
  .quick-action-dropdown {
    width: 100% !important;
    
    .el-dropdown {
      width: 100% !important;
      display: block !important;
      
      .el-button {
        width: 100% !important;
        height: 48px !important;
        display: flex !important;
        align-items: center !important;
        justify-content: center !important;
        gap: 8px !important;
        margin: 0 !important;
        box-sizing: border-box !important;
      }
    }
  }
}

.system-status {
  .status-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px 0;
    border-bottom: 1px solid #f0f0f0;
    
    &:last-child {
      border-bottom: none;
    }
    
    .status-label {
      font-size: 14px;
      color: #606266;
      flex-shrink: 0;
    }
    
    .status-value {
      font-size: 14px;
      color: #303133;
      font-weight: 500;
      display: flex;
      align-items: center;
      gap: 8px;
      flex: 1;
      justify-content: flex-end;
      
      .status-indicator {
        &.connected {
          color: #67c23a;
        }
        
        &.disconnected {
          color: #f56c6c;
        }
      }
      
      .status-badge {
        padding: 2px 8px;
        border-radius: 12px;
        font-size: 12px;
        font-weight: 500;
        
        &.status-running {
          background-color: #f0f9ff;
          color: #67c23a;
          border: 1px solid #b3e5fc;
        }
        
        &.status-error {
          background-color: #fef2f2;
          color: #f56c6c;
          border: 1px solid #fecaca;
        }
      }
      
      .status-bar {
        width: 60px;
        height: 6px;
        background-color: #f0f0f0;
        border-radius: 3px;
        overflow: hidden;
        
        .status-bar-fill {
          height: 100%;
          border-radius: 3px;
          transition: all 0.3s ease;
        }
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .welcome-content {
    flex-direction: column;
    text-align: center;
    gap: 20px;
    
    .welcome-actions {
      justify-content: center;
    }
  }
  
  :deep(.quick-actions-grid) {
    grid-template-columns: 1fr !important;
    grid-template-rows: repeat(4, 1fr) !important;
  }
}
</style>
